import React, { useRef, FC, useImperativeHandle, useState, useEffect, forwardRef } from 'react'
import { withRouter } from 'react-router-dom'
import MyTable from '@/components/common/table'
import JdApi from '@/api/jd'
import { Button, Input, DatePicker, Select, Modal, Spin, Upload, Table, Form, Steps, Row, Col, Tabs, Card, Radio, message } from 'antd';
import { useHistory } from 'react-router-dom'
import { modalLayoutSm } from '@/config/layout';
import $axios from '@/utils/axios';
import {
  PlusCircleOutlined,
  PlusOutlined,
  MinusCircleOutlined
} from '@ant-design/icons';
import './index.less';
const { Option } = Select;
const { Step } = Steps;
const { TabPane } = Tabs;
const TemplateList: FC = () => {
  // const query = getQuery()
  // const { type } = query

  const tableRef: RefType = useRef()
  const UploadFileActionRef: RefType = useRef()
  const history = useHistory()

  const columns = [
    {
      title: '模板名称',
      dataIndex: 'tplName',
    },
    {
      title: '模板说明',
      dataIndex: 'fileExplain',
    },
    // {
    //   title: '更新时间',
    //   dataIndex: 'state',
    //   render:(text,record,index)=>{
    //     return '2021-09-08 16:32'
    //   }
    // },
    {
      title: '操作',
      dataIndex: 'operations',
      render: (txt, record) => (
        <>
          <Button className="btn" onClick={() => detail(record)} size="small">编辑</Button>
          <Button className="btn" style={{marginLeft:'10px'}} onClick={() => del(record)} size="small">删除</Button>
        </>
      )
    }
  ]

  // 新增按钮
  const AddBtn = () => (
    <Button className="fr" onClick={add} type="primary">
      导入模板
    </Button>
  )
  // 新增按钮
  const BatchDel = () => (
    <Button style={{ marginLeft: '10px' }} className="fr" onClick={add} type="default" >
      批量删除
    </Button>
  )
  // 添加
  const add = () => {
    UploadFileActionRef.current.init()
  }
  // 详情
  const detail = (detail) => {
    UploadFileActionRef.current.initDetail(detail.id)
  }
  // 删除
  const del = (record: any) => {
    Modal.confirm({
      title: '确认删除模板 - ' + record.tplName + '？',

      onOk() {
        JdApi.deleteTemplate(record.id).then(() => {
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  // 搜索栏配置项
  const searchConfigList = [
    {
      key: 'tplName',
      slot: <Input placeholder="请输入关键字" allowClear />,
      rules: [],
      initialValue: ''
    },
  ]
  return (
    <>
      <div>
        {/* <BatchDel /> */}
        <AddBtn />
      </div>


      <MyTable
        apiFun={JdApi.getTemplateList}
        columns={columns}
        ref={tableRef}
        searchConfigList={searchConfigList}
        extraProps={{ results: 10 }}
       
      />
      <UploadFileActionCom ref={UploadFileActionRef} callback={() => {
        tableRef.current.update();
      }} />
    </>
  )
}


let onProgress1 = null;
//新建/修改
const UploadFileAction = (props, refs) => {
  const [form] = Form.useForm()
  // const [fileList,setfileList] = useState([]);
  const [formdatavalues, setformdata] = useState(null);
  const [fileName, setFileName] = useState('');
  const [isUploading, setUploading] = useState(false);
  const { setFieldsValue, resetFields } = form
  const [loading, setLoading] = useState<boolean>(false)
  //step
  const [step, setstep] = useState(0);
  const [id, setid] = useState('');
  // sheet list
  const [sheetList, setSheetList] = useState([]);
  // sheet detail
  const [sheetDetailId, setSheetDetailId] = useState(null);

  let handokRequest = null;
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  const AddSheetActionRef: RefType = useRef()
  const SheetDetailRef: RefType = useRef()
  useImperativeHandle(refs, () => ({
    init: (id) => {
      showModal();
      setFileName('');
      setUploading(false);
      // setfileList([]);
    },
    initDetail: (id) => {
      toSheet(id);

    }
  }))
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
    setUploading(false);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      let url = '/jd/data/file/template/save';
      let withCredentials = false;
      let headers = {

      }
      let file = Obj['file'].split('.');
      let fileType = file[file.length - 1];
      let newFormaData = formdatavalues;
      for (let e in Obj) {
        // newFormaData.append(e, Obj[e]);
      }
      Obj['fileType'] = fileType;
      const keys = Object.keys(Obj)
      url = keys.reduce((pre, cur) => `${pre}${cur}=${Obj[cur]}&`, url + '?')
      url = encodeURI(url.substr(0, url.length - 1))
      setLoading(true);
      $axios
        .post(url, formdatavalues, {
          withCredentials,
          headers,
          onUploadProgress: ({ total, loaded }) => {
            console.log(Math.round((loaded / total) * 100).toFixed(2));
          },
        })
        .then((res) => {
          toSheet(res['data']['id']);
        })
        .catch((err) => {
          setLoading(false);
        });


    }).catch(info => {

    })
  };
  //保存
  const handlesave = (values) => {
    console.log(values);
  }
  const toSheet = (d_id) => {
    setid(d_id);
    showModal();
    setFileName('');
    setstep(1);
    getInfo(d_id);
  }
  const getInfo = (qid?) => {
    let q_id = qid ? qid : id;
    $axios.get('/jd/data/file/template/info/' + q_id).then((res) => {
      let data = res['data']['sheetTemplates']
      setSheetList(data)
    })
  }
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setLoading(false);
    resetFields();
    setstep(0);
    setSheetList([]);
    setSheetDetailId(null);
    props.callback && props.callback();
  };
  const uploadprops = {
    // // 'customRequest':customRequest
    // name: 'file',
    // action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    // headers: {
    //   authorization: 'authorization-text',
    // },
    action: '/dm/api/v1/common/file/upload',
    multiple: false,
    data: {},
    headers: {
      Authorization: '$prefix $token',
    },
    onStart(file) {
      console.log('onStart', file, file.name);
      setFileName(file.name);
      setFieldsValue({
        file: file.name
      })
    },
    onSuccess(res, file) {
      console.log('onSuccess', res, file.name);
    },
    onError(err) {
      console.log('onError', err);
    },
    onProgress({ percent }, file) {
      console.log('onProgress', `${percent}%`, file.name);
    },
    customRequest({
      action,
      data,
      file,
      filename,
      headers,
      onError,
      onProgress,
      onSuccess,
      withCredentials,
    }) {
      onProgress1 = onProgress;
      const formData = new FormData();
      if (data) {
        Object.keys(data).forEach(key => {
          formData.append(key, data[key]);
        });
      }
      formData.append(filename, file);
      setformdata(formData);
      return {
        abort() {
          console.log('upload progress is aborted.');
        },
      };
    }
  };
  const toSheetDetail = (id) => {
    setSheetDetailId(null);
    setTimeout(() => {
      setSheetDetailId(id)
    }, 100);

  }
  const columns = [
    {
      title: 'Sheet模板',
      key: 'sheetName',
      dataIndex: 'sheetName',
      render: (txt, record) => {
        return <a onClick={() => toSheetDetail(record.id)}>{txt}</a>
      }
    },
    {
      title: '操作',
      key: 'scan',
      dataIndex: 'scan',
      width: "100px",
      render: (txt, record) => {
        return <div>
          <a onClick={() => toSheetDetail(record.id)} style={{ marginRight: '10px' }}>详情</a>
          <a onClick={() => del(record)}>删除</a>
        </div>
      }
    },
  ]

  // 添加
  const add = () => {
    AddSheetActionRef.current.init(id)
  }
  // 详情
  const detail = (detail) => {
    // UploadFileActionRef.current.initDetail(detail.id)
  }
  // 删除
  const del = (record: any) => {
    Modal.confirm({
      title: '确认删除模板？',

      onOk() {
        $axios.delete('/jd/data/Sheet/template/delete/' + record.id).then((res) => {
          getInfo();
          if (sheetDetailId == record.id) {
            setSheetDetailId(null);
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  return <Modal
    title={step === 0 ? "导入文件" : '编辑模板'}
    visible={isModalVisible}
    onOk={handleOk}
    onCancel={handleCancel}
    centered={true}
    width={step === 0?700:1000}
    maskClosable={false}
    bodyStyle={{
      height: step === 0?240:window.innerHeight - 150,
      overflowY: 'auto'
    }}
    footer={
      <>
        {
          step === 0 && <>
            <Button onClick={handleCancel}>取消</Button>
            <Button onClick={handleOk} type="primary">下一步</Button>
          </>
        }
        {
          step === 1 && <>
            <Button onClick={handleCancel}>关闭</Button>
            {/* <Button onClick={()=>setstep(0)} type="ghost">上一步</Button> */}
            {/* <Button onClick={()=>SheetDetailRef.current.save()} type="primary">保存</Button> */}
          </>
        }

      </>
    }
  >
    {/* <Steps size="small" current={step} style={{marginBottom:'50px'}}>
        <Step title="文件信息" />
        <Step title="sheet模板" />
      </Steps> */}
    {
      step === 0 && <div >
        <Spin spinning={loading}>
          <Form form={form} {...modalLayoutSm}>
            <Form.Item
              name="tplNname"
              label="文件模板名称"
              rules={[
                {
                  required: true,
                  message: '请输入文件模板名称'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="file"
              label="模板文件"
              rules={[
                {
                  required: true,
                  message: '请选择文件'
                }
              ]}
            >
              <Upload {...uploadprops} style={{ width: '100%' }} showUploadList={false}>
                <div style={{ cursor: 'pointer' }}>
                  <Input value={fileName} className="pointer" style={{ width: '545px' }} disabled addonAfter="浏览" placeholder="选择文件" />
                </div>

              </Upload>
            </Form.Item>
            <Form.Item
              name="fileExplain"
              label="文件模板说明"
            >
              <Input.TextArea />
            </Form.Item>
            
          </Form>
        </Spin>
      </div>
    }
    {
      step === 1 && <>
        
        <Row gutter={16}>
          <Col span={8}>
            <Table
              bordered={true}
              pagination={false}
              columns={columns}
              dataSource={sheetList}
            />
            <div style={{ textAlign: 'center', marginBottom: '10px',marginTop:'20px' }}><Button onClick={add} type="primary" icon={<PlusOutlined />} >新增模板</Button></div>
          </Col>
          <Col span={16}>
          {
              sheetDetailId && <div><SheetDetailCom id={sheetDetailId} ref={SheetDetailRef} callback={(values) => {
                handlesave(values);
              }} /></div>
            }

          </Col>
        </Row>
       
       
      </>
    }
    <AddSheetActionCom ref={AddSheetActionRef} callback={() => {
      getInfo();
    }} />

  </Modal>
}
const UploadFileActionCom = forwardRef(UploadFileAction);



//新增sheet
const AddSheetAction = (props, refs) => {
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [sheetName, setsheetName] = useState('');
  const [id, setid] = useState('');
  useImperativeHandle(refs, () => ({
    init: (id) => {
      setid(id);
      showModal();
    }
  }))
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    if(sheetName==''){
      message.error('模板名称必填');
      return;
    }
    let params = {
      "sheetName": sheetName,
      "fid": id,
      "tags": [],
      "keywords": [],
      "dataZones": []
    }
    $axios.post('/jd/data/Sheet/template/save?fid=' + id, params).then((res) => {
      handleCancel();
    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setsheetName('');
    setid('');
    props.callback && props.callback();
  };
  return <Modal
    title="新建模板"
    visible={isModalVisible}
    onOk={handleOk}
    onCancel={handleCancel}
    centered={true}
    width={700}>

    <Input placeholder="模板名称" value={sheetName} onChange={(e) => setsheetName(e.target.value)} />
  </Modal>
}

const AddSheetActionCom = forwardRef(AddSheetAction);




//sheet详情
const SheetDetail = (props, refs) => {
  const [sheetDetail, setsheetDetail] = useState(null);
  const [dtList, setDtList] = useState([]);
  const EditTagFormatRef: RefType = useRef();
  useImperativeHandle(refs, () => ({
    save: () => {
      props.callback && props.callback(sheetDetail);
    }
  }))
  useEffect(() => {
    getInfo();
    getDtQeury();
  }, [])
  const getInfo = () => {
    $axios.get('/jd/data/Sheet/template/info/' + props.id).then((res) => {
      let data = res['data'];
      //关键字
      let keywords = data['keywords'].concat([]);
      keywords.map((e, i) => {
        keywords[i]['table_i'] = getTableRowCol(e['rowIdx'], e['colIdx']);
      })

      //数据
      let dataZones = data['dataZones'].concat([]);
      dataZones.map((e, i) => {

        let dataStart = getTableRowCol(e['dataStartRow'], e['dataStartCol']);
        let dataEnd = getTableRowCol(e['dataEndRow'], e['dataEndCol']);
        dataZones[i]['dataStart'] = dataStart;
        dataZones[i]['dataEnd'] = dataEnd;
        dataZones[i]['tagRowStartColStr'] = rowKeys[e['tagRowStartCol']];
        dataZones[i]['tagRowEndColStr'] = rowKeys[e['tagRowEndCol']];
      })

      //标签

      let tags = data['tags'].concat([]);
      tags.map((e, i) => {
        tags[i]['table_i'] = getTableRowCol(e['rowIdx'], e['colIdx']);
      })

      data = {
        ...data,
        ...{
          keywords: keywords,
          dataZones: dataZones,
          tags: tags
        }
      }
      setsheetDetail(res['data']);
    })
  }
  const getDtQeury = () => {
    $axios.post('/dm/api/baseinfo/dtField/query', {
      "pageNum": 0,
      "pageSize": 100000
    }).then((res) => {
      let list = res['data']['list'] ? res['data']['list'] : [];
      setDtList(list);
    })
  }
  const save = () => {
    let data = {
      ...sheetDetail,
      ...{}
    };

    //关键字
    let keywords = data['keywords'].concat([]);
    keywords.map((e, i) => {
      let keyWordRCkey = getTableRowColKey(e['table_i']);
      keywords[i]['rowIdx'] = keyWordRCkey['row'];
      keywords[i]['colIdx'] = keyWordRCkey['col'];
    })

    //数据
    let dataZones = data['dataZones'].concat([]);
    dataZones.map((e, i) => {
      let dataZonesRCStartkey = getTableRowColKey(e['dataStart']);
      let dataZonesRCEndkey = getTableRowColKey(e['dataEnd']);
      dataZones[i]['dataStartRow'] = dataZonesRCStartkey['row'];
      dataZones[i]['dataStartCol'] = dataZonesRCStartkey['col'];
      dataZones[i]['dataEndRow'] = dataZonesRCEndkey['row'];
      dataZones[i]['dataEndCol'] = dataZonesRCEndkey['col'];
      dataZones[i]['tagRowStartCol'] = rowKeys.indexOf(e['tagRowStartColStr']);
      dataZones[i]['tagRowEndCol'] = rowKeys.indexOf(e['tagRowEndColStr']);
    })
    //标签

    let tags = data['tags'].concat([]);
    tags.map((e, i) => {

      if (e['fixedType'] == 2) {
        tags[i]['rowIdx'] = -1;
        tags[i]['colIdx'] = -1;
      } else {
        let tagRCkey = getTableRowColKey(e['table_i']);
        tags[i]['rowIdx'] = tagRCkey['row'];
        tags[i]['colIdx'] = tagRCkey['col'];
      }

    })

    $axios.put('/jd/data/Sheet/template/update', data).then((res) => {
      message.success('保存成功');
      getInfo();
    })
  }
  //获取行列名称
  const getTableRowCol = (rowIdx, colIdx) => {
    if (rowIdx != -1 && colIdx != -1) {
     
      if (rowIdx == -1 || colIdx == -1) {
        return '';
      } else {
        return rowKeys[colIdx] + (rowIdx + 1);
      }

    } else {
      return '';
    }

  }
  //获取行列row col   参数 'A12'
  const getTableRowColKey = (str) => {
    let row = str.replace(/[^a-z]+/gi, "")
    let col = str.replace(/[^0-9]/ig, "") ? Number(str.replace(/[^0-9]/ig, "")) : 0
    if (str == '') {
      return {
        row: -1,
        col: -1
      }
    }
    if (row && col) {
      return {
        "col": rowKeys.indexOf(row),
        "row": Number(col) - 1
      }
    } else {
      return false;
    }

  }
  //修改关键字
  const changeKeywordsData = (key, value, index) => {
    let keywords = sheetDetail['keywords'].concat([]);
    keywords[index][key] = value;
    setsheetDetail({
      ...sheetDetail,
      ...{
        'keywords': keywords
      }
    })
  }
  //修改数据
  const changeDataZonesData = (key, value, index) => {
    let dataZonesNew = sheetDetail['dataZones'].concat([]);
    dataZonesNew[index][key] = value;
    setsheetDetail({
      ...sheetDetail,
      ...{
        'dataZones': dataZonesNew
      }
    })
  }
  //修改标签
  const changeTagsData = (key, value, index) => {
    let tags = sheetDetail['tags'].concat([]);
    tags[index][key] = value;
    setsheetDetail({
      ...sheetDetail,
      ...{
        'tags': tags
      }
    })
  }

  return <div className="cardSheetDetailWrap">
    {
      sheetDetail && <Card title={sheetDetail['sheetName']} actions={[
        <Button type="primary" onClick={() => save()} >保存</Button>
      ]}>
        <div className="cardHeader">
          <div className="cardTitle">关键字</div>
          <div className="addBtn" onClick={() => {
            setsheetDetail({
              ...sheetDetail,
              ...{
                keywords: sheetDetail['keywords'].concat([{
                  "colIdx": "",//列
                  "keyword": "",//关键字
                  "kid": "",//主键
                  "matchMode": "",//匹配模式
                  "matchModeDesc": "",//匹配模式描述
                  "rowIdx": "",//行
                  "sid": props.id
                }])
              }
            })
          }}><PlusCircleOutlined /></div>

        </div>
        <div className="keywordsWrap">
          {
            sheetDetail['keywords'].map((e, i) => {
              // {
              //   "colIdx": "列",
              //   "keyword": "关键字",
              //   "kid": "主键",
              //   "matchMode": "匹配模式",
              //   "matchModeDesc": "匹配模式描述",
              //   "rowIdx": "行",
              //   "sid": "sid"
              // }
              let table_i = e['table_i']
              return <div className="keywordsItem" key={i}>
                <div className="detailDelBtn">
                  <MinusCircleOutlined onClick={()=>{
                    let keywords = sheetDetail['keywords'].concat([]);
                    keywords.splice(i,1);
                    setsheetDetail({
                      ...sheetDetail,
                      ...{
                        'keywords': keywords
                      }
                    })
                  }}/>
                </div>
                <div className="table_i">
                  <Input placeholder="单元格" value={table_i} onChange={(e) => {
                    changeKeywordsData('table_i', e.target.value, i)
                  }} />
                </div>
                <div className="keyword">
                  <Input placeholder="关键字" onChange={(e) => {
                    changeKeywordsData('keyword', e.target.value, i)
                  }} value={e['keyword']} />
                </div>
                <div className="matchMode">
                  <Select value={e['matchMode']} onChange={(val) => {
                    changeKeywordsData('matchMode', val, i)
                  }}>
                    <Option value={1}>完全匹配</Option>
                    <Option value={2}>左模糊</Option>
                    <Option value={3}>右模糊</Option>
                    <Option value={4}>模糊</Option>
                  </Select>
                </div>
              </div>
            })
          }
        </div>


        <div className="cardHeader">
          <div className="cardTitle">数据区</div>
          <div className="addBtn" onClick={() => {
            setsheetDetail({
              ...sheetDetail,
              ...{
                dataZones: sheetDetail['dataZones'].concat([{
                  "dataEndCol": "",//数据区域结束列
                  "dataEndRow": "",//数据区域结束行
                  "dataStartCol": "",//数据区域开始列
                  "dataStartRow": "",//数据区域开始行
                  "dataStart": '',
                  "dataEnd": '',
                  "dataType": "",//数据类型
                  "dataZoneName": "",//数据区域名称
                  "fields": [],
                  "id": "",//主键
                  "sid": props.id,
                  "tagColEndRow": "",//标签列结束行
                  "tagColEndRowStr": "",
                  "tagColStartRow": "",//标签列开始行
                  "tagColStartRowStr": "",
                  "tagRowEndCol": "",//标签行结束列
                  "tagRowStartCol": ""//标签行开始列
                }])
              }
            })


          }}><PlusCircleOutlined /></div>
        </div>
        <div className="dataZonesWrap">
        {/* dataZones[i]['tagRowStartColStr'] = rowKeys[e['tagRowStartCol']];
        dataZones[i]['tagRowEndColStr'] = rowKeys[e['tagRowEndCol']]; */}
          {
            sheetDetail['dataZones'].map((e, i) => {
              return <div className="dataZonesItem" key={i}>
                <div className="detailDelBtn">
                  <MinusCircleOutlined onClick={()=>{
                    let dataZones = sheetDetail['dataZones'].concat([]);
                    dataZones.splice(i,1);
                    setsheetDetail({
                      ...sheetDetail,
                      ...{
                        'dataZones': dataZones
                      }
                    })
                  }}/>
                </div>
                <div className="dataZonesFormItem">
                  <div className="dataZonesLabel">数据名称</div>
                  <div className="dataZonesValue">
                    <Input value={e['dataZoneName']} onChange={(e) => {
                      changeDataZonesData('dataZoneName', e.target.value, i)
                    }} />
                  </div>
                </div>
                <div className="dataZonesFormItem">
                  <div className="dataZonesLabel">区域</div>
                  <div className="dataZonesValue">
                    <div className="dataZonesFlex">
                      <div className="dataZonesFlexInput">
                        <Input value={e['dataStart']} onChange={(e) => {
                          changeDataZonesData('dataStart', e.target.value, i)
                        }} />
                      </div>
                      <div className="dataZonesFlexDesc">
                        至
                      </div>
                      <div className="dataZonesFlexInput">
                        <Input value={e['dataEnd']} onChange={(e) => {
                          changeDataZonesData('dataEnd', e.target.value, i)
                        }} />
                      </div>
                    </div>

                  </div>
                </div>
                <div className="dataZonesFormItem">
                  <div className="dataZonesLabel">行标签范围</div>
                  <div className="dataZonesValue">
                    <div className="dataZonesFlex">
                      <div className="dataZonesFlexInput">
                        <Input value={e['tagRowStartColStr']} onChange={(e) => {
                          changeDataZonesData('tagRowStartColStr', e.target.value, i)
                        }} />
                      </div>
                      <div className="dataZonesFlexDesc">
                        至
                      </div>
                      <div className="dataZonesFlexInput">
                        <Input value={e['tagRowEndColStr']} onChange={(e) => {
                          changeDataZonesData('tagRowEndColStr', e.target.value, i)
                        }} />
                      </div>
                    </div>

                  </div>
                </div>
                <div className="dataZonesFormItem">
                  <div className="dataZonesLabel">列标签范围</div>
                  <div className="dataZonesValue">
                    <div className="dataZonesFlex">
                      <div className="dataZonesFlexInput">
                        <Input value={e['tagColStartRow']+1} onChange={(e) => {
                          changeDataZonesData('tagColStartRow', Number(e.target.value)-1, i)
                        }} />
                      </div>
                      <div className="dataZonesFlexDesc">
                        至
                      </div>
                      <div className="dataZonesFlexInput">
                        <Input value={e['tagColEndRow']+1} onChange={(e) => {
                          changeDataZonesData('tagColEndRow', Number(e.target.value)-1, i)
                        }} />
                      </div>
                    </div>

                  </div>
                </div>
              </div>
            })
          }
        </div>


        <div className="cardHeader">
          <div className="cardTitle">Sheet标签</div>
          <div className="addBtn" onClick={() => {
            setsheetDetail({
              ...sheetDetail,
              ...{
                tags: sheetDetail['tags'].concat([{
                  "colIdx": "",//列
                  "fieldId": "",//string
                  "id": "",//主键
                  "rowIdx": "",//行
                  "tag": "",//标签
                  "tagFormat": "",//格式化
                  "tagRegex": "",//提取子串
                  "tagType": "3",//标签类型
                  "fixedType":1, //fixedType
                  "targetID": props.id,//文件或模板ID
                }])
              }
            })
          }}><PlusCircleOutlined /></div>
        </div>

        <div className="tagsWrap">
          {
            sheetDetail['tags'].map((e, i) => {

              let tagFormat = e['tagFormat'] ? e['tagFormat'] : ''
              return <div className="tagsItem" key={i}>
                <div className="detailDelBtn">
                  <MinusCircleOutlined onClick={()=>{
                    let tags = sheetDetail['tags'].concat([]);
                    tags.splice(i,1);
                    setsheetDetail({
                      ...sheetDetail,
                      ...{
                        'tags': tags
                      }
                    })
                  }}/>
                </div>
                <div className="tagsFormItem">
                  <Radio.Group onChange={(e) => changeTagsData('fixedType', e.target.value, i)} value={e['fixedType']}>
                    <Radio value={1}>指定单元格</Radio>
                    <Radio value={2}>指定标签值</Radio>
                  </Radio.Group>
                </div>
                <div className="tagsFormItem">
                  <div className="tagsLabel">标签</div>
                  <div className="tagsValue">
                    <Input value={e['tag']} onChange={(e) => {
                      changeTagsData('tag', e.target.value, i)
                    }} />
                  </div>
                </div>
                {
                  e['fixedType'] == 2&&<>
                    <div className="tagsFormItem">
                      <div className="tagsLabel">标签类型</div>
                      <div className="tagsValue">
                        <Select value={e['tagType']} style={{ width: '100%' }} onChange={(val) => {
                          changeTagsData('tagType', val, i)
                        }} >
                         <Option value={3}>sheet模板标签</Option>
                         <Option value={4}>file模板标签</Option>

                         </Select>
                      </div>
                    </div>
                  </>
                }
                <div className="tagsFormItem">
                  <div className="tagsLabel">元数据</div>
                  <div className="tagsValue">
                    <Select value={e['fieldId']} style={{ width: '100%' }} onChange={(val) => {
                      changeTagsData('fieldId', val, i)
                    }} >
                      {
                        dtList.map((e) => {
                          return <Option value={e['id']}>{e['fieldName']}</Option>
                        })
                      }
                    </Select>
                  </div>
                </div>
                {
                  e['fixedType'] == 1 && <>
                    
                    <div className="tagsFormItem">
                      <div className="tagsLabel">标签单元格</div>
                      <div className="tagsValue">
                        <Input value={e['table_i']} onChange={(e) => {
                          changeTagsData('table_i', e.target.value, i)
                        }} />
                      </div>
                    </div>
                    <div className="tagsFormItem">
                      <div className="tagsLabel">格式化</div>
                      <div className="tagsValue" onClick={() => { }}>
                        <Input value={tagFormat} disabled className="tagFormat" addonAfter={<div onClick={()=>EditTagFormatRef.current.init(tagFormat,i)}>修改</div>} />
                      </div>
                    </div>
                  </>
                }

              </div>
            })
          }
        </div>


      </Card>
    }
    <EditTagFormatCom ref={EditTagFormatRef} callback={(val,i)=>{
      changeTagsData('tagFormat', val, i)
    }}/> 
  </div>
}

const SheetDetailCom = forwardRef(SheetDetail);

//编辑格式化内容
const EditTagFormat =  (props, refs) => {
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [list,SetList] = useState([]);
  const [tagIndex,setTagIndex] = useState(1);
  useImperativeHandle(refs, () => ({
    init: (val:string,index:number) => {
      if(val==''){
        SetList([]);
      }else{
        SetList(JSON.parse(val));
      }
      setTagIndex(index);
      showModal();
    },
  }))
  const showModal = ()=>{
    setIsModalVisible(true);
  }
  const handleOk = () => {
    props.callback && props.callback(JSON.stringify(list),tagIndex);
    handleCancel();
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    
  };

  const changeListData = (key, value, index) => {
    let listNew = list.concat([]);
    listNew[index][key] = value;
    SetList(listNew);
  }
  return <Modal
    title="格式化"
    visible={isModalVisible}
    onOk={handleOk}
    onCancel={handleCancel}
    centered={true}
    width={700}>
      <div>
        {
          list.map((e,i)=>{
            return <div className="tagFormatItem" key={i}>
              <div className="tagFormatType">
                <Select value={e['type']} style={{width:'100%'}} onChange={(val) => {
                      changeListData('type', val, i)
                    }} >
                  <Option value="replace">替换</Option>
                  <Option value="match">提取</Option>
                </Select>
              </div>
              <div className="tagFormatArgu">
                <Input placeholder="正则" style={{width:'100%'}} value={e['argu1']} onChange={(e) => {
                    changeListData('argu1', e.target.value, i)
                  }} />
              </div>
              {
                e['type']=='replace'&&<>
                   <div className="tagFormatContent">替换为</div>
                  <div className="tagFormatType">
                    <Input placeholder="正则" style={{width:'100%'}} value={e['argu2']} onChange={(e) => {
                        changeListData('argu2', e.target.value, i)
                      }} />
                  </div>
                </>
              }
              <div className="tagFormMinusOutlined">
                <MinusCircleOutlined onClick={()=>{
                   let listNew = list.concat([]);
                   listNew.splice(i,1);
                   SetList(listNew);
                }}/>
              </div>
            </div>
          })
        }
      </div>
      <div>
        <Button onClick={()=>{
          let listNew = list.concat([{
            type:'replace',// reolace  match
            argu1:'',
            argu2:'',
          },]);
          SetList(listNew);
        }}>新增<PlusCircleOutlined /></Button>
      </div>
  </Modal>
}
const EditTagFormatCom = forwardRef(EditTagFormat);

const tagFormatList = [
  {
    type:'replace',// reolace  match
    argu1:'',
    argu2:'',
  },

  {
    type:'match',// reolace  match
    argu1:'正则',
    argu2:'',
  }
]


const alphabet = ['', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
const alphabet1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
const rowKeys = [];
alphabet.map((e) => {
  alphabet1.map((k) => {
    rowKeys.push(e + k);
  })
})
export default withRouter(TemplateList)

